package com.gitee.feizns.explore.data_structure.linked_list.singly.duplicates;

/**
 * 输入: 1->2->3->3->4->4->5
 * 输出: 1->2->5
 * @author feizns
 * @since 2019/11/1
 */
public class DeleteDuplicates2 {

    public static void main(String[] args) {
        ListNode node = create();
        ListNode listNode = deleteDuplicates(node);
        listNode.print();
    }

    private static ListNode create() {
        ListNode ret = new ListNode(-1);
        ret.next = new ListNode(1);
        ret.next.next = new ListNode(2);
        ret.next.next.next = new ListNode(2);
        ret.next.next.next.next = new ListNode(2);
        return ret;
    }

    public static ListNode deleteDuplicates(ListNode head) {
        ListNode headPrev = new ListNode(-1);
        headPrev.next = head;
        ListNode prev = headPrev;
        ListNode curt = headPrev.next;
        while ( curt != null && curt.next != null ) {
            if ( curt.val != curt.next.val ) {
                prev = curt;
                curt = curt.next;
            } else {
                ListNode node = nextUnique(curt.next);
                prev.next = node;
                curt = node;
            }
        }
        return headPrev.next;
    }

    private static ListNode nextUnique(ListNode node) {
        int val = node.val;
        ListNode curt = node.next;
        while ( curt != null && curt.val == val ) {
            curt = curt.next;
        }
        return curt;
    }

}
